<template>
  <div class="flex justify-center items-center w-full h-full">
    <div class="w-[800px] h-full">
      <div
        ref="chatContainerRef"
        class="w-full h-[calc(100%-120px)] pr-5 overflow-y-auto scrollbar-thumb-gray-400 scrollbar-track-gray-100 scrollbar-thin scroll-smooth"
      >
        <Welcome
          icon="https://mdn.alipayobjects.com/huamei_iwk9zp/afts/img/A*s5sNRo5LjfQAAAAAAAAAAAAADgCCAQ/fmt.webp"
          title="您好 我是AI助手小王"
          description="有什么可以帮你的吗？~"
          class="mb-4 bg-white"
        />
        <div class="flex flex-col gap-4">
          <!-- <Bubble
            placement="end"
            content="Hi, good morning, I'm fine!"
            :avatar="{
              src: user
            }"
          >
            <template #header>
              <div class="flex">
                <span class="text-gray-500">2025-03-25 14:11:30</span>
              </div>
            </template>
          </Bubble>
          <Bubble
            placement="start"
            content="Good morning, how are you?"
            :avatar="{
              src: 'https://mdn.alipayobjects.com/huamei_iwk9zp/afts/img/A*s5sNRo5LjfQAAAAAAAAAAAAADgCCAQ/fmt.webp'
            }"
          >
            <template #header>
              <div class="flex gap-2">
                <span>GoCargo</span>
                <span class="text-gray-500">2025-03-25 14:10:55</span>
              </div>
            </template>
          </Bubble> -->

          <!-- <div class="flex gap-2">
            <el-button
              @click="
                () => {
                  count++
                }
              "
            >
              Add Bubble
            </el-button>
          </div> -->

          <BubbleList ref="listRef" :roles="rolesAsObject" :items="chatMessages" />
        </div>
      </div>
      <div class="w-full h-[100px] mt-2">
        <div
          class="flex justify-center items-center cursor-pointer hover:scale-105"
          @click="createNewDialog"
        >
          <svg-icon name="new_dialog" class="!w-[122px] !h-[32px] pb-4"></svg-icon>
        </div>
        <Sender
          placeholder="有什么我能帮你的吗？"
          :value="searchValue"
          :loading="searchLoading"
          @change="handleChange"
          @cancel="handleCancel"
          @submit="handleSubmit"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  // 消息气泡
  Bubble,
  BubbleList,
  // 发送框
  Sender,
  Welcome
} from 'ant-design-x-vue'
import user from '@/assets/images/user.png'
import { getAiResponse } from '@/api/ai'
import { useDateFormat, useNow } from '@vueuse/core'
import { useUserStore } from '@/stores/modules/user'
import { ElMessage } from 'element-plus'
import { nextTick, watch, onMounted, onUnmounted } from 'vue'

const curTime = useDateFormat(useNow(), 'YYYY-MM-DD HH:mm:ss')
const userStore = useUserStore()

const userId = userStore.userId
const searchValue = ref('')

userStore.conversationId = Math.random().toString(36).slice(-8)

const chatMessages = ref([])

const handleGetAiResponse = async () => {
  // 先添加用户消息
  chatMessages.value.push({
    key: Date.now(),
    role: 'user',
    content: searchValue.value,
    header: h('span', { class: 'text-[#828282]' }, curTime.value)
  })

  // 添加一条带loading的AI消息
  const aiMessageKey = Date.now()
  chatMessages.value.push({
    key: aiMessageKey,
    role: 'ai',
    loading: true,
    header: h('div', { class: 'flex items-center gap-2' }, [
      h('span', { class: 'font-bold' }, 'AI助手小王'),
      h('span', { class: 'text-[#828282]' }, curTime.value)
    ])
  })

  try {
    const formData = new FormData()
    formData.append('conversation_id', userStore.conversationId)
    formData.append('user_id', userId)
    formData.append('user_input', searchValue.value)
    const res = await getAiResponse(formData)

    // 直接替换最后一条消息
    chatMessages.value[chatMessages.value.length - 1] = {
      key: aiMessageKey,
      role: 'ai',
      content: res.finish ? res.json_response : res.response,
      loading: false,
      header: h('div', { class: 'flex items-center gap-2' }, [
        h('span', { class: 'font-bold' }, 'AI助手小王'),
        h('span', { class: 'text-[#828282]' }, curTime.value)
      ])
    }
  } catch (error) {
    // 错误时也直接替换最后一条消息
    chatMessages.value[chatMessages.value.length - 1] = {
      key: aiMessageKey,
      role: 'ai',
      content: '抱歉，获取回复失败，请重试',
      loading: false,
      header: h('div', { class: 'flex items-center gap-2' }, [
        h('span', { class: 'font-bold' }, 'AI助手小王'),
        h('span', { class: 'text-[#828282]' }, curTime.value)
      ])
    }
    console.error('获取AI响应失败:', error)
    ElMessage.error('获取回复失败，请重试')
  } finally {
    searchLoading.value = false
  }
}

const searchLoading = ref(false)
const handleSubmit = () => {
  if (!searchValue.value.trim()) {
    ElMessage.warning('请输入内容')
    return
  }
  searchLoading.value = true
  handleGetAiResponse()
  searchValue.value = ''
}
const handleChange = (value) => {
  searchValue.value = value
}
const handleCancel = () => {
  searchLoading.value = false
}

const rolesAsObject = {
  ai: {
    placement: 'start',
    avatar: {
      src: 'https://mdn.alipayobjects.com/huamei_iwk9zp/afts/img/A*s5sNRo5LjfQAAAAAAAAAAAAADgCCAQ/fmt.webp'
    },
    // header: 'AI助手 小王',

    typing: { step: 5, interval: 20 },
    style: {
      maxWidth: '600px'
    }
  },
  user: {
    avatar: { src: user },
    placement: 'end'
    // header: (item) => ({
    //   content: h('div', { class: 'flex gap-2 justify-end' }, [
    //     h('span', { class: 'text-gray-500' }, item.timestamp)
    //   ])
    // })
  }
}

// const count = ref(3)

const listRef = ref(null)

const chatContainerRef = ref(null)

// 滚动到底部的方法
const scrollToBottom = async () => {
  await nextTick()
  if (chatContainerRef.value) {
    setTimeout(() => {
      chatContainerRef.value.scrollTo({
        top: chatContainerRef.value.scrollHeight,
        behavior: 'smooth'
      })
    }, 500)
  }
}

// 监听消息列表变化
watch(
  () => chatMessages.value.length,
  () => {
    scrollToBottom()
  }
)
// 监听每条消息的内容变化（用于处理loading状态变为实际内容时的滚动）
watch(
  () => chatMessages.value,
  () => {
    scrollToBottom()
  },
  { deep: true }
)

const createNewDialog = () => {
  userStore.conversationId = Math.random().toString(36).slice(-8)
  chatMessages.value = []
}

// 处理页面关闭
onMounted(() => {
  window.addEventListener('beforeunload', handleBeforeUnload)
})

onUnmounted(() => {
  userStore.conversationId = ''
  window.removeEventListener('beforeunload', handleBeforeUnload)
})

const handleBeforeUnload = () => {
  userStore.conversationId = ''
}
</script>
